#!/usr/bin/env python3
"""
示例配置文件生成器
为不同的开发工具生成相应的配置
"""

import json
import os
from typing import Dict, Any

def create_roo_code_config() -> Dict[str, Any]:
    """创建Roo Code配置"""
    return {
        "apiProvider": {
            "type": "openai",
            "id": "deepspeed-qwen3-coder",
            "name": "DeepSpeed MOE + Qwen3-Coder",
            "baseUrl": "http://localhost:8000",
            "apiKey": "roo-code-key-2024",
            "models": [
                {
                    "id": "qwen3-coder-480b-a35b-instruct",
                    "name": "Qwen3-Coder 480B (MOE)",
                    "description": "基于DeepSpeed MOE优化的Qwen3-Coder模型，专门针对代码生成和调试进行了优化",
                    "contextLength": 262144,
                    "inputPrice": 0.0,
                    "outputPrice": 0.0,
                    "supportsFunctionCalling": True,
                    "supportsVision": False,
                    "maxTokens": 4096
                }
            ],
            "supportsStreaming": True,
            "customHeaders": {
                "Content-Type": "application/json",
                "User-Agent": "RooCode/DeepSpeed-MOE-Client"
            }
        },
        "customCommands": [
            {
                "name": "生成代码",
                "prompt": """你是一个专业的代码助手。请根据用户的需求生成相应的代码，包括：
- 清晰注释和文档字符串
- 遵循最佳实践
- 错误处理
- 单元测试示例

用户需求: {需求}""",
                "requiresContext": False
            },
            {
                "name": "调试代码", 
                "prompt": """你是一个经验丰富的调试专家。请分析并调试用户提供的代码：
1. 识别潜在错误和问题
2. 提供详细的错误分析
3. 给出修复方案
4. 解释修复原理

需要调试的代码:
{代码}""",
                "requiresContext": True
            },
            {
                "name": "代码审查",
                "prompt": """你是一个资深的软件工程师和代码审查专家。请对提供的代码进行全面审查：

审查维度：
- 代码质量和可读性
- 性能和效率
- 安全性和最佳实践
- 可维护性和扩展性
- 测试覆盖度

需要审查的代码:
{代码}""",
                "requiresContext": True
            },
            {
                "name": "优化代码",
                "prompt": """你是一个性能优化专家。请优化提供的代码，重点关注：
- 算法复杂度优化
- 内存使用优化
- I/O操作优化
- 并发处理优化
- 代码结构改进

待优化代码:
{代码}""",
                "requiresContext": True
            },
            {
                "name": "架构设计",
                "prompt": """你是一个系统架构专家。请根据用户需求设计软件架构：

设计原则：
- 模块化和可维护性
- 可扩展性和灵活性
- 性能和可靠性
- 安全性和合规性

用户需求:
{需求}""",
                "requiresContext": False
            }
        ],
        "slashCommands": [
            {
                "name": "/explain",
                "description": "详细解释代码功能和工作原理",
                "prompt": "请详细解释以下代码的功能、工作原理和关键设计思路："
            },
            {
                "name": "/refactor", 
                "description": "重构代码以提高质量和可维护性",
                "prompt": "请重构以下代码，使其更加清晰、高效和可维护："
            },
            {
                "name": "/test",
                "description": "为代码生成全面的测试用例",
                "prompt": "请为以下代码生成全面的单元测试和集成测试用例："
            },
            {
                "name": "/document",
                "description": "为代码添加详细的文档",
                "prompt": "请为以下代码添加详细的文档字符串和注释："
            },
            {
                "name": "/optimize",
                "description": "优化代码性能",
                "prompt": "请优化以下代码的性能和资源使用："
            }
        ],
        "globalRules": [
            "始终提供清晰、准确的代码示例",
            "解释关键概念和设计决策",
            "考虑安全性和最佳实践",
            "包含错误处理和边界情况",
            "提供测试用例和验证方法"
        ]
    }

def create_claude_code_config() -> Dict[str, Any]:
    """创建Claude Code配置"""
    return {
        "anthropic": {
            "apiKey": "claude-code-key-2024",
            "baseUrl": "http://localhost:8000",
            "models": [
                {
                    "id": "qwen3-coder-480b-a35b-instruct",
                    "name": "Qwen3-Coder 480B (MOE)",
                    "description": "基于DeepSpeed MOE优化的Qwen3-Coder模型，专为代码开发设计",
                    "contextLength": 262144,
                    "inputPrice": 0.0,
                    "outputPrice": 0.0,
                    "supportsFunctionCalling": True,
                    "supportsVision": False
                }
            ],
            "defaultModel": "qwen3-coder-480b-a35b-instruct"
        },
        "tools": {
            "enabled": [
                "bash",
                "grep", 
                "file_ops",
                "parallel_search",
                "glob",
                "todo_write",
                "insert_into_file",
                "str_replace_based_edit_tool",
                "search_replace_editor",
                "lsp"
            ]
        },
        "workspace": {
            "ignoredFiles": [
                "node_modules",
                ".git",
                "__pycache__",
                "*.pyc",
                ".env",
                "dist",
                "build"
            ]
        }
    }

def create_continue_dev_config() -> Dict[str, Any]:
    """创建Continue.dev配置"""
    return {
        "models": [
            {
                "title": "Qwen3-Coder (DeepSpeed MOE)",
                "provider": "openai",
                "model": "qwen3-coder-480b-a35b-instruct",
                "apiKey": "local-dev-key-2024",
                "apiBase": "http://localhost:8000",
                "contextLength": 262144,
                "completionOptions": {
                    "temperature": 0.1,
                    "topP": 0.95,
                    "maxTokens": 4096
                }
            }
        ],
        "tabAutocompleteModel": {
            "title": "Qwen3-Coder Autocomplete",
            "provider": "openai",
            "model": "qwen3-coder-480b-a35b-instruct",
            "apiKey": "local-dev-key-2024",
            "apiBase": "http://localhost:8000",
            "completionOptions": {
                "temperature": 0.2,
                "topP": 0.9,
                "maxTokens": 100
            }
        },
        "embeddingsProvider": {
            "provider": "transformers.js"
        },
        "customCommands": [
            {
                "name": "/test",
                "prompt": "{{{ input }}}\n\nGenerate comprehensive unit tests for this code.",
                "description": "Generate unit tests for the selected code"
            },
            {
                "name": "/refactor",
                "prompt": "{{{ input }}}\n\nRefactor this code to improve its readability, performance, and maintainability.",
                "description": "Refactor the selected code"
            },
            {
                "name": "/optimize", 
                "prompt": "{{{ input }}}\n\nOptimize this code for better performance and efficiency.",
                "description": "Optimize the selected code"
            },
            {
                "name": "/explain",
                "prompt": "{{{ input }}}\n\nExplain how this code works and its key concepts.",
                "description": "Explain the selected code"
            }
        ],
        "slashCommands": [
            {
                "name": "/document",
                "description": "Add documentation to the selected code",
                "prompt": "Add comprehensive documentation and comments to this code:"
            },
            {
                "name": "/review",
                "description": "Review and suggest improvements for the code",
                "prompt": "Review this code and suggest improvements:"
            }
        ],
        "ui": {
            "fontSize": 14,
            "fontFamily": "JetBrains Mono, Fira Code, Consolas, monospace",
            "theme": "dark"
        }
    }

def create_vscode_settings() -> Dict[str, Any]:
    """创建VSCode设置"""
    return {
        # Continue.dev配置
        "continue.apiKey": "local-dev-key-2024",
        "continue.apiBase": "http://localhost:8000",
        "continue.useOpenAi": True,
        "continue.defaultModel": "qwen3-coder-480b-a35b-instruct",
        "continue.tabAutocompleteModel": {
            "title": "Qwen3-Coder Autocomplete",
            "provider": "openai",
            "model": "qwen3-coder-480b-a35b-instruct",
            "apiKey": "local-dev-key-2024",
            "apiBase": "http://localhost:8000"
        },
        "continue.contextProviders": [
            {
                "name": "diff",
                "params": {}
            },
            {
                "name": "folder",
                "params": {}
            },
            {
                "name": "open",
                "params": {}
            },
            {
                "name": "codebase",
                "params": {}
            },
            {
                "name": "docs",
                "params": {}
            },
            {
                "name": "open",
                "params": {}
            },
            {
                "name": "terminal",
                "params": {}
            },
            {
                "name": "problems",
                "params": {}
            },
            {
                "name": "selection",
                "params": {}
            }
        ],
        
        # 编辑器配置
        "editor.fontSize": 14,
        "editor.fontFamily": "JetBrains Mono, Fira Code, Consolas, monospace",
        "editor.lineNumbers": "on",
        "editor.wordWrap": "on",
        "editor.tabSize": 4,
        "editor.insertSpaces": True,
        "editor.detectIndentation": False,
        
        # 文件关联
        "files.associations": {
            "*.py": "python",
            "*.js": "javascript", 
            "*.ts": "typescript",
            "*.jsx": "javascriptreact",
            "*.tsx": "typescriptreact",
            "*.json": "json",
            "*.yml": "yaml",
            "*.yaml": "yaml"
        },
        
        # Python特定配置
        "python.defaultInterpreterPath": "./venv/bin/python",
        "python.formatting.provider": "black",
        "python.linting.enabled": True,
        "python.linting.pylintEnabled": True,
        "python.testing.pytestEnabled": True,
        
        # 终端配置
        "terminal.integrated.defaultProfile.linux": "bash",
        "terminal.integrated.defaultProfile.osx": "bash", 
        "terminal.integrated.defaultProfile.windows": "PowerShell",
        
        # 主题和图标
        "workbench.colorTheme": "Dark+ (default dark)",
        "workbench.iconTheme": "vs-seti",
        
        # 自动保存和格式化
        "files.autoSave": "afterDelay",
        "files.autoSaveDelay": 1000,
        "editor.formatOnSave": True,
        "editor.formatOnType": True,
        "editor.formatOnPaste": True,
        
        # 智能提示
        "editor.suggest.showMethods": True,
        "editor.suggest.showProperties": True,
        "editor.suggest.showFunctions": True,
        "editor.suggest.showConstructors": True,
        "editor.suggest.showVariables": True,
        "editor.suggest.showFields": True,
        
        # 调试配置
        "python.defaultSettings": {
            "justMyCode": False
        }
    }

def create_neovim_config() -> str:
    """创建Neovim配置"""
    return '''-- Neovim配置 for DeepSpeed MOE + Qwen3-Coder
-- 安装依赖:
-- :PackerInstall
-- :CocInstall coc-pyright coc-tsserver

-- 插件管理器
local packer = require('packer')

-- 安装插件
packer.startup(function(use)
    -- 包管理器
    use 'wbthomason/packer.nvim'
    
    -- LSP配置
    use 'neovim/nvim-lspconfig'
    use 'williamboman/mason.nvim'
    use 'williamboman/mason-lspconfig.nvim'
    
    -- 代码补全
    use 'hrsh7th/nvim-cmp'
    use 'hrsh7th/cmp-nvim-lsp'
    use 'hrsh7th/cmp-buffer'
    use 'hrsh7th/cmp-path'
    use 'hrsh7th/cmp-vsnip'
    use 'hrsh7th/vim-vsnip'
    
    -- AI代码助手 (这里可以配置类似Continue的插件)
    use 'github/copilot.vim'
    
    -- 语法高亮
    use 'nvim-treesitter/nvim-treesitter'
    
    -- 文件浏览器
    use 'kyazdani42/nvim-tree.lua'
    
    -- 状态栏
    use 'nvim-lualine/lualine.nvim'
    
    -- 终端
    use 'voldikss/vim-floaterm'
    
    -- 主题
    use 'folke/tokyonight.nvim'
end)

-- 基本设置
vim.o.number = true
vim.o.relativenumber = true
vim.o.tabstop = 4
vim.o.softtabstop = 4
vim.o.shiftwidth = 4
vim.o.expandtab = true
vim.o.autoindent = true
vim.o.smartindent = true
vim.o.wrap = false
vim.o.clipboard = "unnamedplus"
vim.o.undofile = true
vim.o.backup = false
vim.o.writebackup = false

-- 颜色主题
vim.cmd[[colorscheme tokyonight]]

-- 插件配置
require('nvim-tree').setup()
require('lualine').setup()
require('mason').setup()
require('mason-lspconfig').setup()

-- LSP配置
local lspconfig = require('lspconfig')
lspconfig.pyright.setup{}
lspconfig.tsserver.setup{}
lspconfig.jsonls.setup{}

-- 代码补全配置
local cmp = require('cmp')
cmp.setup({
    snippet = {
        expand = function(args)
            vim.fn["vsnip#anonymous"](args.body)
        end,
    },
    mapping = {
        ['<C-b>'] = cmp.mapping(cmp.mapping.scroll_docs(-4), { 'i', 'c' }),
        ['<C-f>'] = cmp.mapping(cmp.mapping.scroll_docs(4), { 'i', 'c' }),
        ['<C-Space>'] = cmp.mapping(cmp.mapping.complete(), { 'i', 'c' }),
        ['<C-e>'] = cmp.mapping(cmp.mapping.close(), { 'i', 'c' }),
        ['<CR>'] = cmp.mapping.confirm({ select = true }),
    },
    sources = cmp.config.sources({
        { name = 'nvim_lsp' },
        { name = 'buffer' },
    })
})

-- 快捷键
vim.keymap.set('n', '<leader>ff', ':NvimTreeToggle<CR>', {})
vim.keymap.set('n', '<leader>ft', ':FloatermToggle<CR>', {})
vim.keymap.set('n', '<leader>fm', ':Mason<CR>', {})
'''

def save_all_configs():
    """保存所有配置文件"""
    print("正在生成配置文件...")
    
    # 确保输出目录存在
    os.makedirs("configs", exist_ok=True)
    
    # 生成配置文件
    configs = {
        "roo-code-config.json": create_roo_code_config(),
        "claude-code-config.json": create_claude_code_config(),
        "continue-dev-config.json": create_continue_dev_config(),
        "vscode-settings.json": create_vscode_settings(),
        "neovim-init.lua": create_neovim_config()
    }
    
    for filename, config in configs.items():
        filepath = f"configs/{filename}"
        with open(filepath, 'w', encoding='utf-8') as f:
            if filename.endswith('.lua'):
                f.write(config)
            else:
                json.dump(config, f, indent=2, ensure_ascii=False)
        print(f"✓ 已生成: {filepath}")
    
    print("\n配置文件生成完成！")
    print("\n使用说明:")
    print("1. Roo Code: 将 configs/roo-code-config.json 导入Roo Code设置")
    print("2. Claude Code: 使用 configs/claude-code-config.json 配置")
    print("3. Continue.dev: 将 configs/continue-dev-config.json 导入VSCode设置")
    print("4. VSCode: 将 configs/vscode-settings.json 导入VSCode设置")
    print("5. Neovim: 将 configs/neovim-init.lua 复制到 ~/.config/nvim/init.lua")

if __name__ == "__main__":
    save_all_configs()